package edu.gyc.mysystem.controller;

import edu.gyc.mysystem.dao.UserMapper;
import edu.gyc.mysystem.model.User;
import edu.gyc.mysystem.service.UserRoleService;
import edu.gyc.mysystem.shiro.ShaTest;
import edu.gyc.mysystem.vo.UserRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Controller
@Slf4j
public class UserController {
    @GetMapping("/login")
    public String login() {


        return "/";
    }

    @PostMapping("/login")
    public String dologin(User user, HttpServletRequest request) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        Subject  subject= SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
            User userinfo = (User) subject.getPrincipal();
            userinfo.setPassword("");
            subject.getSession().setAttribute("user", user);
        } catch (Exception e) {
            String msg = "";
            if (e instanceof UnknownAccountException) {
                msg = "用户名错误了！";
            }
            else if(e instanceof IncorrectCredentialsException){
                msg = "密码错误了！";
            }else {
                msg=e.getMessage();
            }

            request.setAttribute("msg", msg);
            return "login";
        }
        return "menu";
    }

    /**
     * 登出  这个方法没用到,用的是shiro默认的logout
     * 在ShiroConfig//logout是shiro提供的过滤器
     *  filterChainDefinitionMap.put("/logout", "logout");
     *  若要使用可以注释上面这个方法，就可调用下面方法注销用户
     */

    @RequestMapping("/logout")
    public String logout() {

        Subject subject = SecurityUtils.getSubject();
        log.info(((User)subject.getPrincipal()).getUsername()+"退出系统.");
        subject.logout();


        return "/";
    }

    @GetMapping("/reg")
    public String reg() {
        return "/reg";
    }
   @Autowired
    UserMapper userMapper;
    @PostMapping("/reg")
    public String doreg(String username, String password, Model model) {
        boolean isSuccess=false;
        String msg = "";

      User userInfo=userMapper.selectByUsername(username);
        if (userInfo != null) {
            msg="用户名已被使用，换一个吧！";
            model.addAttribute("msg", msg);
            model.addAttribute("isSuccess", isSuccess);
            return "/reg";
        }

        String salt = RandomStringUtils.randomAlphabetic(6);
        String newpass = ShaTest.make(password,salt);

        User newUser=new User();
        newUser.setUsername(username);
        newUser.setPassword(newpass);
        newUser.setSalt(salt);
        userMapper.insert(newUser);
        msg="恭喜你注册成功！";
        model.addAttribute("msg", msg);
        isSuccess=true;
        model.addAttribute("isSuccess", isSuccess);
        return "/reg";

    }

    @Autowired
    UserRoleService userRoleService;

    @RequestMapping("/user/roleuser")
    public String userRole(Model model) {
        Set<UserRoleVo> userRoleVoSet=userRoleService.getUserRoles();
        model.addAttribute("userroles", userRoleVoSet);
        return "/admin/userrole";
    }
}
